<script lang="ts" setup>
import {onMounted, reactive, watch} from 'vue'
import { ref } from 'vue'
import Upload from "@/views/UserCenter/Upload.vue";
import {ElMessage,ElMessageBox,FormInstance} from "element-plus";
import {useUserStore} from '@/stores/user.js'
import {updateUserInfoAPI} from '@/apis/user'

const form = reactive({
  name: useUserStore().userInfo.username||'',
  sex:'male'
})

//Upload上传头像
const uploadRef = ref()
const callUpload = () => {
  uploadRef.value.submitUpload()
}

const onSubmit = () => {
  //TODO update
  //上传新头像
  callUpload()
  //更改昵称
  useUserStore().alterNickName(form.name)
  //通知后端更新
  updateUserInfoAPI(useUserStore().userInfo)
  ElMessage({
    message: '保存成功',
    type: 'success',
    plain: true,
  })
}

const phoneForm=reactive({
  phoneNumber:'',
  captcha:'',
})
const phoneFormRef = ref<FormInstance>()

const dialogFormVisible = ref(false)

const phoneRules={
  phoneNumber:[
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { min: 11, max: 11, message: '手机号码格式不对', trigger: 'blur' },
  ],
  captcha:[
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '请输入4位有效验证码', trigger: 'blur' },
  ]
}


const seconds=ref(false)
// 创建定时器
let intervalId
//发送短信验证码
function sendMSM() {
  if (phoneForm.phoneNumber.length===11&&seconds.value===false){
    seconds.value=60
    //启动定时器
    intervalId = setInterval(() => {
      seconds.value--;
    }, 1000); // 1000毫秒，即1秒
    //TODO send msm

    ElMessage({
      message: '验证码发送成功',
      type: 'success',
      plain: true,
    })
  }
}

watch(seconds,(newValue,oldValue)=>{
  if(seconds.value===0){
    //清除定时器，防止内存泄漏
    clearInterval(intervalId)
    seconds.value=false
  }
})

const submitPhoneNumber = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      dialogFormVisible.value = false
      //本地更新数据
      useUserStore().bindPhoneNumber(phoneForm.phoneNumber)
      //通知后端更新
      updateUserInfoAPI(useUserStore().userInfo)
      ElMessage({
        message: '绑定成功',
        type: 'success',
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const clearBinding = () => {
  ElMessageBox.confirm(
      '确定解绑当前手机号码？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        //本地更新数据
        useUserStore().bindPhoneNumber('')
        //通知后端更新
        updateUserInfoAPI(useUserStore().userInfo)
        ElMessage({
          type: 'success',
          message: '解绑成功',
        })
      })
      .catch(() => {
      })
}


</script>

<template>
<div class="UC_info">
<div class="formArea">
  <el-form
      :model="phoneForm"
      label-width="auto"
      :rules="phoneRules"
      ref="phoneFormRef"
      style="max-width: 600px">
    <el-form-item label="头像">
      <Upload ref="uploadRef"></Upload>
    </el-form-item>

    <el-form-item label="昵称">
      <el-input
          v-model="form.name"
          style="width: 200px"
          maxlength="10"
          show-word-limit />
    </el-form-item>

    <el-form-item label="手机号码">
      <el-input
          style="width: 200px;margin-right: 20px"
          disabled
          :model-value="useUserStore().userInfo.phone">
      </el-input>

      <el-button
          type="success"
          @click="dialogFormVisible=true"
          v-if="!useUserStore().isBinging">
        绑定
      </el-button>

      <el-button
          type="danger"
          @click="clearBinding"
          v-if="useUserStore().isBinging">
        解绑
      </el-button>

    </el-form-item>

    <el-form-item label="性别">
      <el-radio-group v-model="form.sex" >
        <el-radio value="male">男</el-radio>
        <el-radio value="female">女</el-radio>
      </el-radio-group>
    </el-form-item>


    <el-form-item>
      <el-button style="margin-left: auto" type="primary" @click="onSubmit">保存</el-button>
    </el-form-item>

  </el-form>
</div>
</div>
  <el-dialog v-model="dialogFormVisible" title="绑定手机" width="500" >
    <el-form
        :model="phoneForm"
        :rules="phoneRules"
        ref="phoneFormRef"
        label-width="auto">
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input v-model="phoneForm.phoneNumber" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="验证码" prop="captcha">
        <el-input v-model="phoneForm.captcha" autocomplete="off">
          <template #suffix>
            <span class="send-sms-btn"
                  :style="{'--textColor':phoneForm.phoneNumber.length===11&&!seconds?'rgb(1, 184, 8)':null,
                      '--hoverCursor':phoneForm.phoneNumber.length===11&&!seconds?'pointer':'no-drop',
                      '--hoverColor':phoneForm.phoneNumber.length===11&&!seconds?'rgb(1, 184, 8)':null,}"
                  @click="sendMSM"
            >{{!seconds?'发送验证码':seconds+'s后重新获取'}}</span>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPhoneNumber(phoneFormRef)">
            确认
          </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped lang="less">
.UC_info{
  width: 990px;
  height: 600px;
  background-color: white;
  border-radius: 10px;

  padding: 0 20px;
}
.formArea{
  padding: 20px 20px;
}
.el-form-item{

  margin-bottom: 35px;
}
.send-sms-btn{
  color:var(--textColor);
  border: none;
  background-color: rgba(255, 255, 255, 0);
  font-size: 14px;
}

.send-sms-btn:hover{
  color:var(--hoverColor);
  cursor: var(--hoverCursor);
}
</style>